<template>
  <div class="list-view" v-loading="loading">
    <div class="list-container" v-if="list && list.length > 0">
      <div class="card" v-for="(item, key) in list" :key="key">
        <div @click="showDialog(item, key)" class="item">
          <div class="collect-icon" v-if="item.collect === 1">
            <img src="../../../assets/home/collect-icon.png" alt />
          </div>
          <div class="top-img">
            <img v-lazy="item.cover" alt />
          </div>
          <div class="infoView">
            <div class="title">{{ item.work_name }}</div>
            <div class="tit" v-html="$decodeHtmlEntities(item.description).replace(/&nbsp;/g, '')"></div>
            <div class="user-info">
              <div class="ava">
                <img :src="item.avatar || defaultImg" alt />
              </div>
              <div class="username" style="color:#4c4c4c">{{ item.username }}</div>
            </div>
          </div>
          <div class="status-box start-box">
            <div class="pinjia" v-if="item.score">
              <div class="ispfBtn">
                <strong style="font-weight: blid; font-size: 22px; color: #4c4c4c">
                  {{
                  item.score
                  }}
                </strong>
                分
              </div>
            </div>
            <div class="pinjia" v-else>
              <div class="pfBtn" @click="showDialog(item, key)">去评分</div>
            </div>

            <div class="xingji" v-if="item.collect === 1">
              <div class="isxjBtn" @click.stop="toCollect(item.work_id)">取消星级</div>
            </div>
            <div class="xingji" v-else>
              <div class="xjBtn" @click.stop="toCollect(item.work_id)">设为星级</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <no-data></no-data>
    </div>
    <el-dialog
      :visible.sync="showdialogDetail"
      :before-close="beforeClose"
      :close-on-click-modal="false"
      lock-scroll
    >
      <div @click="prevWork" v-show="currentIndex > 0" class="arrow-left">
        <img src="@/assets/home/arrow-left.png" alt />
        <div class="text">上一作品</div>
      </div>
      <div class="popbox" v-if="currentIndex !== null">
        <div class="pop-left">
          <div class="info-view">
            <div class="img-status" v-if="list[currentIndex].score !==0  && comment">
              <img src="@/assets/home/Reviewed.png" alt />
            </div>
            <div class="img-status" v-else>
              <img src="@/assets/home/not-reviewed.png" alt />
            </div>
            <div class="left-top">
              <div class="info-title">{{ list[currentIndex].work_name }}</div>
            </div>
            <div class="left-center">
              <div class="userInfo-box">
                <div class="ava-box">
                  <img :src="list[currentIndex].avatar || defaultImg" alt />
                </div>
                <div class="username" style="color:#4c4c4c">{{ list[currentIndex].username }}</div>
              </div>
              <div class="description">
                <div v-html="$decodeHtmlEntities(list[currentIndex].description).replace(/&nbsp;/g, '')" class="desc"></div>
              </div>
            </div>
          </div>
          <div class="img-list">
            <!-- <img v-lazy="list[currentIndex].cover" alt /> -->
            <el-image
              v-for="(url, index) in workImages"
              :key="index"
              :src="url"
              :preview-src-list="workImages"
              style="width:100%; display: block;"
            ></el-image>
          </div>
        </div>
        <div class="pop-right">
          <div class="right-view">
            <h1 style="margin-bottom: 20px">
              作品评分
              <span style="color: red">*</span>
            </h1>
            <div class="right-box" v-for="(item, index) in dimensions" :key="index">
              <h2 class="work-title">{{ item.title }} (共{{ item.score }}分)</h2>
              <div class="con-box">{{ item.content }}</div>
              <div class="score-box">
                <div class="prebox">
                  <el-progress :percentage="item.percentage" color="#00bfd6" :show-text="false"></el-progress>
                </div>
                <span style="color: #00bfd6">
                  (
                  <el-input
                    class="no-border"
                    v-model.number="item.teacher_score"
                    @input="updatePercentage(index)"
                  ></el-input>)
                  <span style="margin-left: 10px">分</span>
                </span>
              </div>
            </div>
            <div class="right-box">
              <h4>
                总计：
                <span style="color: #00bfd6" class="work-title">{{ totalScore }} 分</span>
              </h4>
            </div>
            <div class="right-box">
              <h2 class="work-title">
                作品评语
                <span style="color: red">*</span>
              </h2>
              <div class="enter-top">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 3,}"
                  maxlength="600"
                  placeholder="请填写评语"
                  v-model="comment"
                  show-word-limit
                  @input="validateComment"
                ></el-input>
                <p
                  v-if="errors.comment"
                  style="color: red; font-size:12px; margin-top:10px"
                >{{ errors.comment }}</p>
              </div>
              <div class="enter-bottom">
                <el-button class="button1" @click="toCancel(currentIndex)">提交</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div @click="nextWork" v-show="currentIndex < list.length - 1" class="arrow-right">
        <img src="@/assets/home/arrow-right.png" alt />
        <div class="text">下一作品</div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import NoData from "../../../components/Nodata.vue";
import { getEditThird, getWorksDimension, getCollect } from "@/api/index";
export default {
  name: "CreateList",
  components: {
    NoData
  },
  data() {
    return {
      srcList: [
        "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
        "https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg"
      ],
      colors: ["#4d4d4d"],

      isPf: true, //是否评分

      loading: false,
      showdialogDetail: false, // 弹窗预览详情
      swiperList: [], //轮播数组
      currentIndex: null, //切换值

      // 图片报错加在默认图片
      defaultImg: require("@/assets/default-header.png"),
      work_id: null,
      comment: null,
      totalScore: 0,
      dimensions: [],
      errors: {
        comment: ""
      },
      isErr: false
    };
  },
  computed: {
    // 计算每个维度的百分比
    percentages() {
      return this.dimensions.map(item => {
        if (
          item.score === 0 ||
          isNaN(item.teacher_score) ||
          isNaN(item.score)
        ) {
          return 0; // 如果分母为零或任何值不是数字，则返回0
        }
        return parseFloat(((item.teacher_score / item.score) * 100).toFixed(2));
      });
    },
    workImages() {
      try {
        return JSON.parse(this.list[this.currentIndex].work_images) || [];
      } catch (e) {
        console.error("Failed to parse work_images:", e);
        return [];
      }
    }
  },
  watch: {
    // 监听 dimensions 数组的变化，以更新 percentage
    dimensions: {
      deep: true,
      handler() {
        this.dimensions.forEach((item, index) => {
          item.percentage = this.percentages[index];
        });
      }
    }
  },
  methods: {
    validateComment() {
      if (!this.comment || this.comment.trim() === "") {
        this.errors.comment = "评语不能为空";
        this.isErr = true;
      } else if (this.comment.length > 600) {
        this.errors.comment = "评语不能超过600个字符";
        this.isErr = true;
      } else {
        this.errors.comment = null; // 清除错误
        this.isErr = false;
      }
    },
    toCollect(id) {
      getCollect({ work_id: id }).then(res => {
        this.$message.success(res.msg);
        this.$emit("onUpdate");
      });
    },
    getDimension(id) {
      getWorksDimension({ work_id: id }).then(res => {
        this.dimensions = res.list;
        if (res.comment && res.comment.content) {
          this.comment = res.comment.content;
        } else {
          this.comment = "";
        }
        this.dimensions.forEach((item, index) => {
          if (!item.teacher_score || item.teacher_score == "null") {
            item.teacher_score = 0;
          }
          item.percentage = this.percentages[index];
        });
        this.calculateTotalScore();
      });
    },

    updatePercentage(index) {
      const item = this.dimensions[index];
      if (item.teacher_score === "") {
        this.$message.error("请输入对应分数");
        item.teacher_score = 0;
        return;
      }
      if (item.teacher_score - item.score > 0) {
        this.$message.error("输入的值过大，请重新输入");
        item.teacher_score = 0;

        return;
      }
      if (typeof item.teacher_score === "string") {
        // 尝试将字符串转换为数字
        const num = parseFloat(item.teacher_score);
        if (!isNaN(num)) {
          item.teacher_score = num;
        } else {
          // 如果转换失败，保持原样或给出提示
          this.$message.error("请输入有效的数字！");
          return;
        }
      }
      if (item.score === 0 || isNaN(item.teacher_score) || isNaN(item.score)) {
        item.percentage = 0; // 如果分母为零或任何值不是数字，则设置为0
      } else {
        item.percentage = parseFloat(
          ((item.teacher_score / item.score) * 100).toFixed(2)
        );
      }
      this.calculateTotalScore();
      // console.log("当前键入：", this.dimensions);
    },
    calculateTotalScore() {
      // 计算总分的逻辑
      this.totalScore = this.dimensions.reduce((acc, item) => {
        return acc + (item.teacher_score || 0);
      }, 0);
      if (this.totalScore) {
        this.list[this.currentIndex].score = this.totalScore;
      }
    },
    beforeClose() {
      this.currentIndex = null;
      this.dimensions = [];
      this.totalScore = 0;
      this.percentage = 0;
      this.comment = null;
      this.$emit("onUpdate");
      this.showdialogDetail = false;
    },
    toCancel(key) {
      let hasError = false;
      this.validateComment();
      if (this.isErr) {
        hasError = true;
        return;
      }
      var formData = new FormData();
      this.dimensions.forEach((dimension, index) => {
        if (!dimension.teacher_score) {
          this.$message.error("请输入对应维度分数");
          hasError = true;
          return; // 如果有错误，立即停止循环
        }
        if (dimension.teacher_score > dimension.score) {
          dimension.teacher_score = 0;
          this.$message.error("评分不能超过维度分数");
          hasError = true;
          return; // 如果有错误，立即停止循环
        }

        formData.append(
          `info[${dimension.id}][score]`,
          dimension.teacher_score
        );
      });
      if (hasError) {
        return; // 如果有错误，直接返回，不再继续执行
      }
      formData.append("comment", this.comment);
      formData.append("work_id", this.list[key].work_id);

      getEditThird(formData)
        .then(res => {
          if (res.code === 0) {
            this.$message.success(res.msg);
            // this.$emit("onUpdate"); // 传递操作结果给父组件
          } else {
            this.$message.error("提交失败，请稍后再试");
          }
        })
        .catch(err => {
          this.$message.error("提交失败，请稍后再试");
        });
    },

    // 显示弹窗
    showDialog(item, index) {
      // this.list = [item];
      this.currentIndex = index;
      this.showdialogDetail = true;
      this.totalScore = this.list[index].score || 0;
      this.getDimension(this.list[index].work_id);
    },
    prevWork() {
      this.currentIndex--;
      if (this.currentIndex < 0) {
        this.currentIndex = this.list.length - 1;
      }
      this.comment = null;
      this.getDimension(this.list[this.currentIndex].work_id);
      this.totalScore = this.list[this.currentIndex].score || 0;
    },
    nextWork() {
      this.currentIndex++;
      if (this.currentIndex >= this.list.length) {
        this.currentIndex = 0;
      }
      this.comment = null;
      this.getDimension(this.list[this.currentIndex].work_id);
      this.totalScore = this.list[this.currentIndex].score || 0;
    }
  },

  // props: ["list", "level"],
  props: {
    list: {
      type: Array,
      default: () => []
    }
  }
};
</script>
<style scoped>
>>>.el-image__preview{
cursor: zoom-in;
}
>>> .el-image-viewer__mask {
  opacity: 1;
}
>>> .el-image__inner {
  margin-bottom: 15px;
}
.list-view {
  width: 100%;
}
.list-container {
  display: flex;
  flex-wrap: wrap;
  max-width: 1720px;
  margin: 40px auto;
}
.card {
  width: 328px;
  background: #fff;
  overflow: hidden;

  display: inline-block;
  position: relative;
  margin: 0 20px 20px 0;
  z-index: 0;
}
.card:nth-child(5n) {
  margin-right: 0;
}
.card .item {
  cursor: pointer;
  position: relative;
}
.card .item .collect-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 26px;
  height: 26px;

  z-index: 99;
}
.card .item .collect-icon img {
  width: 100%;
}
.card .top-img {
  position: relative;
  width: 328px;
  height: 226px;
  display: block;
  border-radius: 6px;
  background: #e5e5e5;
}
.card .top-img img {
  width: 100%;
  height: 100%;
  border-radius: 6px;
  object-fit: cover;
}
>>>.card .infoView .title {
  line-height: 20px;
  color: #1a1a1a;
  font-weight: 500 !important;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 20px;
}
>>> .card .infoView .tit {
  height: 36px;
  margin: 14px 0;
  font-size: 14px;
  line-height: 18px;
  color: #4d4d4d !important;
  font-weight: 500 !important;
  white-space: wrap;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
>>>.card .infoView .tit p,
>>>.card .infoView .tit p>b,
>>>.card .infoView .tit p>strong{
   font-size: 14px;
  line-height: 18px;
  color: #4d4d4d !important;
  font-weight: 500 !important;
}
.card .infoView {
  margin: 16px 0;
}
.card .infoView .user-info {
  display: flex;
  align-items: center;
}
.card .infoView .user-info .ava {
  width: 26px;
  height: 26px;
  background: #ffffff;
  border-radius: 50%;
  margin-right: 10px;
}
.card .infoView .user-info img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.status-box {
  margin: 20px 0;
  display: flex;
  align-items: center;
}
.status-box .isOk,
.status-box .isOut {
  cursor: pointer;
  color: #1a1a1a;
  width: 120px;
  height: 38px;
  background: #f3f4f3;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.status-box .isOk {
  margin-right: 20px;
}
.status-box .isOk .round,
.status-box .isOut .round {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #666666;
  margin-right: 10px;
}
.status-box .isOk .txt,
.status-box .isOut .txt {
  font-size: 16px;

  line-height: 18px;
}
.status-box .isOk.active,
.status-box .isOut.active {
  color: #fff;
  background: #00bfd6;
}
.status-box .isOk.active > .round,
.status-box .isOut.active > .round {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #fff;
  box-sizing: border-box;
  padding: 1px;
  background: transparent;
}

.status-box .isOk.active > .round .inner-round,
.status-box .isOut.active > .round .inner-round {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #fff;
}
.pinjia .pxBtn {
  width: 120px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  font-size: 16px;
  color: #ffffff;
  background: #00bfd6;
  border-radius: 6px;
  cursor: pointer;
}
.start-box {
  display: flex;
}
.start-box .pinjia .pfBtn {
  width: 120px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  font-size: 16px;
  color: #ffffff;
  background: #00bfd6;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 20px;
}
.start-box .pinjia .ispfBtn {
  width: 120px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  font-size: 16px;
  color: #4c4c4c;
  background: #f4f4f4;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 20px;
}
.start-box .xingji .isxjBtn {
  width: 120px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  font-size: 16px;
  color: #4c4c4c;
  background: #f4f4f4;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 20px;
}
.start-box .xingji .xjBtn {
  width: 120px;
  height: 38px;
  line-height: 38px;
  text-align: center;
  font-size: 16px;
  color: #00bfd6;
  background: #f4f4f4;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 20px;
}
.swiper-top {
  height: 100%;
}
>>> .el-dialog__body {
  padding: 0;
}
.popbox {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.pop-left {
  position: relative;
  width: 1200px;
  height: auto;
  margin: 0 auto;
  padding-bottom: 100px;
  box-sizing: border-box;
  background-color: #fff;
}
.pop-left .info-view {
  padding: 70px 100px 60px;
  position: relative;
}
.popbox .pop-left .info-view .img-status {
  position: absolute;
  top: 30px;
  right: 60px;
  width: 122px;
  height: 96px;
  margin: 0 auto;
  padding-bottom: 60px;
}
.popbox .pop-left .info-view .img-status img {
  width: 100%;
}
.pop-left .left-top .info-title {
  font-size: 40px;
  color: #000000;
  line-height: 32px;
}
.pop-left .left-center .userInfo-box {
  display: flex;
  align-items: center;
  margin-top: 60px;
  margin-bottom: 30px;
}
.pop-left .left-center .userInfo-box .ava-box {
  width: 40px;
  height: 40px;
  margin-right: 10px;
  border-radius: 50%;
  overflow: hidden;
  background: #ffffff;
}
.pop-left .left-center .userInfo-box .ava-box img {
   width: 100%;
  height: 100%;
  display: block;
   border-radius: 50%;
}
.pop-left .left-center .userInfo-box .username {
  font-size: 16px;
  color: #4c4c4c;
}
.pop-left .description {
  font-size: 20px;
  color: #000000;
  line-height: 32px;
}
.pop-left .img-list img {
  display: block;
  width: 100%;
  height: auto;
  margin: 10px auto;
}
.pop-left .status-box {
  margin: 40px auto;
  justify-content: center;
}
.popbox .pop-right .right-view {
  margin-left: 20px;
  box-sizing: border-box;
  width: 400px;
  /* max-height: 1200px; */
  background-color: white;
  padding: 60px 30px;
}
.popbox .pop-right .right-box {
  margin-bottom: 60px;
  margin-left: 10px;
}

.popbox .pop-right .right-box h1 {
  font-weight: 400;
  font-size: 24px;
  color: #1a1a1a;
  padding-bottom: 20px;
}
.popbox .pop-right .right-box .work-title {
  font-weight: 400;
  font-size: 20px;
  color: #1a1a1a;
  padding-bottom: 14px;
}
.popbox .pop-right .right-box .work-title .con-box {
  font-weight: 400;
  font-size: 16px;
  color: #666666;
  padding-bottom: 20px;
}

.popbox .pop-right .right-box .enter-bottom {
  margin-top: 40px;
}
.popbox .pop-right .right-box .enter-bottom .button1 {
  width: 120px;
  height: 44px;
  background: #00bfd6;
  border-radius: 6px;
  color: #fff;
}

>>>.el-icon-close:before {
    content: "\e78d";
}
>>> .el-dialog__header {
  padding: 0;
}
>>> .el-dialog__header .el-dialog__headerbtn {
  top: -20px;
  right: -80px;
  width: 40px;
  height: 40px;
  font-size: 40px;
  /* background: rgba(255, 255, 255, 0.3); */
  border-radius: 50%;
  opacity: .8;
}
>>>.el-image-viewer__btn{
/* background: rgba(255, 255, 255, 0.3); */
}
>>>.el-image-viewer__close{
color: #fff;
}
>>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
>>> .el-dialog {
  /* margin-top: 8vh !important; */
  margin: 5vh auto !important;
  width: 1620px;
  background-color: transparent;
}
.el-dialog__wrapper {
  z-index: 10000 !important;
  background: rgba(0, 0, 0, 0.7);
}
.arrow-left,
.arrow-right {
  position: fixed;
  color: #fff;
  bottom: 10%;
  cursor: pointer;
  z-index: 999;
  height: 60px;
  width: 60px;
  line-height: 60px;
  text-align: center;
  background: #ffffff;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.3);
}
.arrow-left {
  left: 20px;
}
.arrow-left img,
.arrow-right img {
  vertical-align: middle;
  width: 13px;
  height: 24px;
}

.arrow-right {
  right: 40px;
  /* margin-right: 40px; */
}
.text {
  margin-top: 10px;
  font-size: 12px;
  color: #ffffff;
  line-height: 32px;
  opacity: 0.3;
}
.arrow-left:hover .text,
.arrow-right:hover .text {
  opacity: 1;
}
.no-border {
  font-size: 20px;
  font-weight: bold;
  color: #00bfd6;
  width: 50px;
  /* height: 30px;
  line-height: 30px; */
  /* border-bottom: 1px solid #00bfd6; */
}
>>> .no-border .el-input__inner {
  color: #00bfd6;
  border: none !important;
  padding: 0 6px;
  text-align: center;
}
>>> .no-border .el-input__inner:focus {
  border: none !important;
}
.popbox .pop-right .right-box .score-box {
  display: flex;
  align-items: baseline;
}
.popbox .pop-right .right-box .score-box .prebox {
  width: 180px;
  margin-right: 30px;
}
>>> .el-progress-bar {
  margin-right: -68px;
}
>>> .el-progress__text {
  margin-left: 20px;
}
</style>
